﻿@using RuoVea.OmiArticle.Options
@using RuoVea.ExDto
@using RuoVea.OmiArticle.Attributes
@using RuoVea.OmiArticle
@using RuoVea.OmiArticle.Language
@{
    Layout = "";
    AppConfig config = ConfigManages.Config ?? new AppConfig();
}
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@Html.Raw(i18n.content_editing)</title>
    <link href="~/ruoveaui/xg6rvft8p/avue/index.css" rel="stylesheet" />
    <link href="~/ruoveaui/xg6rvft8p/elementui/index.min.css" rel="stylesheet" />
    <style>
        .el-button [class*="el-icon-"] + span { margin-left: 1px !important; }
        .avatar-uploader .el-upload { border: 1px dashed #d9d9d9; border-radius: 6px; cursor: pointer; position: relative; overflow: hidden;}
        .avatar-uploader .el-upload:hover { border-color: #409EFF;}
        .avatar-uploader-icon {font-size: 28px;color: #8c939d;width: 178px;height: 178px;line-height: 178px;text-align: center;}
        .avatar {width: 356px;height: 178px;display: block;}
    </style>
</head>
<body>
    <div id="app" v-cloak>
        <div class="avue-form">
            <el-form ref="form" style="overflow-x: hidden;" :model="form" :rules="rules" label-width="100px" loading="loading">
                <el-form-item :label="i18n.t('title')" prop="title">
                    <el-input v-model="form.title" maxlength="120" size="mini" show-word-limit />
                </el-form-item>
                <el-row :gutter="20">
                    <el-col :span="14">
                        <el-form-item :label="i18n.t('category')" prop="categorieId">
                            <el-select v-model="form.categorieId" size="mini" filterable :placeholder="i18n.t('please_select_category')">
                                <el-option v-for="c in categoryOptions" :key="c.id" :label="c.name" :value="c.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item :label="i18n.t('status')">
                            <el-radio-group v-model="form.status" size="mini"> <el-radio v-for="item in statusData" :key="item.value" :label="item.value">{{ item.label }}</el-radio> </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="14">
                        <el-form-item :label="i18n.t('tags')">
                            <el-select v-model="form.tagIds" size="mini" multiple filterable :placeholder="i18n.t('please_select_tags')">
                                <el-option v-for="t in tagOptions" :key="t.id" :label="t.name" :value="t.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item :label="i18n.t('sort')">
                            <el-input-number v-model="form.sort" size="mini" :min="0" :step="10" :max="100000">
                            </el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-collapse accordion>
                    <el-collapse-item :title="i18n.t('extended_settings')" name="1">

                        <el-form-item :label="i18n.t('subtitle')">
                            <el-input type="textarea" size="mini" :rows="2" v-model="form.subtitle" maxlength="255" show-word-limit />
                        </el-form-item>

                        <el-form-item :label="i18n.t('summary')">
                            <el-input type="textarea" size="mini" :rows="3" v-model="form.summary" maxlength="500" show-word-limit />
                        </el-form-item>

                <el-form-item :label="i18n.t('cover_image')">
                    <el-upload 
                        class="avatar-uploader" 
                        :action="uploadUrl" 
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload" >
                        <img v-if="form.coverImage" :src="form.coverImage" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>

                        <el-row :gutter="20">
                            <el-col :span="6">
                                <el-form-item :label="i18n.t('is_top')">
                                    <el-radio-group v-model="form.isTop" size="mini"><el-radio v-for="item in yesnoData" :key="item.value" :label="item.value">{{ item.label }}</el-radio> </el-radio-group>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item :label="i18n.t('is_featured')">
                                    <el-radio-group v-model="form.isFeatured" size="mini"><el-radio v-for="item in yesnoData" :key="item.value" :label="item.value">{{ item.label }}</el-radio></el-radio-group>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item :label="i18n.t('is_comment_allowed')">
                                    <el-radio-group v-model="form.isCommentAllowed" size="min"><el-radio v-for="item in yesnoData" :key="item.value" :label="item.value">{{ item.label }}</el-radio> </el-radio-group>
                                </el-form-item>
                            </el-col>

                        </el-row>
                    </el-collapse-item>
                </el-collapse>

                <el-collapse accordion>
                    <el-collapse-item :title="i18n.t('seo_settings')" name="1">
                        <el-form-item :label="i18n.t('seo_title')">
                            <el-input v-model="form.seo.metaTitle" size="mini" maxlength="120" show-word-limit />
                        </el-form-item>
                        <el-form-item :label="i18n.t('seo_keywords')">
                            <el-input type="textarea" :rows="2" size="mini" v-model="form.seo.metaKeywords" maxlength="255" show-word-limit />
                        </el-form-item>
                        <el-form-item :label="i18n.t('seo_description')">
                            <el-input type="textarea" :rows="3" size="mini" v-model="form.seo.metaDescription" maxlength="500" show-word-limit />
                        </el-form-item>
                        <el-form-item :label="i18n.t('canonical_url')">
                            <el-input v-model="form.seo.canonicalUrl" size="mini" />
                        </el-form-item>
                    </el-collapse-item>
                </el-collapse>

                <el-form-item label="" label-width="0px">
                    <div id="toolbar-container" style="border: 1px solid #ccc; border-bottom: none;"></div>
                    <div id="editor-container" style="border: 1px solid #ccc; border-top: none; min-height:500px;"></div>
                </el-form-item>

                <div class="actions" style="text-align: right;" v-if="type!='view'">
                    <el-button @@click="onClose" size="small">{{i18n.t('close')}}</el-button>
                    <el-button type="primary" @@click="submit" size="small">{{i18n.t('save')}}</el-button>
                </div>
            </el-form>
        </div>
    </div>
    <script src="~/ruoveaui/xg6rvft8p/vue/vue.js"></script>
    <script src="~/ruoveaui/xg6rvft8p/elementui/index.i18n.js"></script>
    <script src="~/ruoveaui/xg6rvft8p/elementui/index.lang.js"></script>
    <script>
        Vue.prototype.i18n.messages.zhCN = { 
            ...Vue.prototype.i18n.messages.zhCN, 
            ...{ "category": "所属分类", "property_value": "属性值", "dictionary_value": "字典值", "is_default": "是否默认",  "Display Text": "显示文本",  "Tag Type": "标签类型",  "Style (Style)": "样式(Style)",  "Style (Class)": "样式(Class)",  "Extended Data": "拓展数据", "title": "标题", "subtitle": "副标题", "summary": "摘要", "cover_image": "封面图片", "seo_title": "SEO标题", "seo_keywords": "SEO关键词", "seo_description": "SEO描述", "canonical_url": "规范URL", "category": "类别", "tags": "标签", "status": "状态", "draft": "草稿", "published": "已发布", "offline": "已下架", "is_top": "置顶", "is_featured": "精选", "view_count": "阅读数", "like_count": "点赞数", "is_comment_allowed": "允许评论", "comments_count": "评论数", "sort": "排序", "modification_record": "修改记录", "parent_node_cannot_select_self": "上级节点不能选择自己", "please_select_category": "请选择分类", "please_select_tags": "请选择标签", "extended_settings": "扩展设置", "seo_settings": "SEO设置", "close": "关闭", "save": "保存", "content_cannot_empty": "内容不能为空", "only_images_allowed": "只能上传图片", "image_size_exceeded": "图片大小不能超过2MB", "cover_upload_success": "封面图片上传成功", "cover_upload_failed": "封面图片上传失败", "image_upload_failed": "图片上传失败"
            } 
        };
        Vue.prototype.i18n.messages.en = { 
            ...Vue.prototype.i18n.messages.en, 
            ...{ "category": "Belongs to Category", "property_value": "Property Value", "dictionary_value": "Dictionary Value", "is_default": "Is Default", "Display Text": "Display Text",  "Tag Type": "Tag Type",  "Style (Style)": "Style (Style)",  "Style (Class)": "Style (Class)",  "Extended Data": "Extended Data", "title": "Title", "subtitle": "Subtitle", "summary": "Summary", "cover_image": "Cover Image", "seo_title": "SEO Title", "seo_keywords": "SEO Keywords", "seo_description": "SEO Description", "canonical_url": "Canonical URL", "category": "Category", "tags": "Tags", "status": "Status", "draft": "Draft", "published": "Published", "offline": "Offline", "is_top": "Top", "is_featured": "Featured", "view_count": "View Count", "like_count": "Like Count", "is_comment_allowed": "Allow Comments", "comments_count": "Comments Count", "sort": "Sort", "modification_record": "Modification Record", "parent_node_cannot_select_self": "Cannot select self as parent node", "please_select_category": "Please select category", "please_select_tags": "Please select tags", "extended_settings": "Extended Settings", "seo_settings": "SEO Settings", "close": "Close", "save": "Save", "content_cannot_empty": "Content cannot be empty", "only_images_allowed": "Only images are allowed", "image_size_exceeded": "Image size cannot exceed 2MB", "cover_upload_success": "Cover image uploaded successfully", "cover_upload_failed": "Cover image upload failed", "image_upload_failed": "Image upload failed"
            } 
        };
        Vue.prototype.i18n.messages.fr = { 
            ...Vue.prototype.i18n.messages.fr, 
            ...{ "category": "Catégorie associée", "property_value": "Valeur de propriété", "dictionary_value": "Valeur de dictionnaire", "is_default": "Par défaut", "Display Text": "Texte affiché",  "Tag Type": "Type de balise",  "Style (Style)": "Style (Style)",  "Style (Class)": "Style (Class)",  "Extended Data": "Données étendues", "title": "Titre", "subtitle": "Sous-titre", "summary": "Résumé", "cover_image": "Image de couverture", "seo_title": "Titre SEO", "seo_keywords": "Mots-clés SEO", "seo_description": "Description SEO", "canonical_url": "URL canonique", "category": "Catégorie", "tags": "Étiquettes", "status": "Statut", "draft": "Brouillon", "published": "Publié", "offline": "Hors ligne", "is_top": "Épinglé", "is_featured": "En vedette", "view_count": "Nombre de vues", "like_count": "Nombre de j'aime", "is_comment_allowed": "Autoriser les commentaires", "comments_count": "Nombre de commentaires", "sort": "Tri", "modification_record": "Historique des modifications", "parent_node_cannot_select_self": "Impossible de se sélectionner soi-même comme nœud parent", "please_select_category": "Veuillez sélectionner une catégorie", "please_select_tags": "Veuillez sélectionner des étiquettes", "extended_settings": "Paramètres étendus", "seo_settings": "Paramètres SEO", "close": "Fermer", "save": "Enregistrer", "content_cannot_empty": "Le contenu ne peut pas être vide", "only_images_allowed": "Seules les images sont autorisées", "image_size_exceeded": "La taille de l'image ne peut pas dépasser 2 Mo", "cover_upload_success": "Image de couverture téléchargée avec succès", "cover_upload_failed": "Échec du téléchargement de l'image de couverture", "image_upload_failed": "Échec du téléchargement de l'image"
            } 
        };
        
        Vue.prototype.i18n.messages.ja = { 
            ...Vue.prototype.i18n.messages.ja, 
            ...{ "category": "所属カテゴリ", "property_value": "プロパティ値",  "dictionary_value": "辞書値", "is_default": "デフォルトかどうか", "Display Text": "表示テキスト",  "Tag Type": "タグの種類",  "Style (Style)": "スタイル（Style）",  "Style (Class)": "スタイル（Class）",  "Extended Data": "拡張データ", "title": "タイトル", "subtitle": "サブタイトル", "summary": "要約", "cover_image": "カバー画像", "seo_title": "SEOタイトル", "seo_keywords": "SEOキーワード", "seo_description": "SEO説明", "canonical_url": "正規URL", "category": "カテゴリ", "tags": "タグ", "status": "ステータス", "draft": "下書き", "published": "公開済み", "offline": "非公開", "is_top": "トップ表示", "is_featured": "おすすめ", "view_count": "閲覧数", "like_count": "いいね数", "is_comment_allowed": "コメント許可", "comments_count": "コメント数", "sort": "並び順", "modification_record": "変更記録", "parent_node_cannot_select_self": "自身を親ノードとして選択できません", "please_select_category": "カテゴリを選択してください", "please_select_tags": "タグを選択してください", "extended_settings": "拡張設定", "seo_settings": "SEO設定", "close": "閉じる", "save": "保存", "content_cannot_empty": "コンテンツを入力してください", "only_images_allowed": "画像のみアップロード可能です", "image_size_exceeded": "画像サイズは2MBを超えることはできません", "cover_upload_success": "カバー画像のアップロードに成功しました", "cover_upload_failed": "カバー画像のアップロードに失敗しました", "image_upload_failed": "画像のアップロードに失敗しました"
            } 
        };
        
        Vue.prototype.i18n.messages.vi = { 
            ...Vue.prototype.i18n.messages.vi, 
            ...{ "category": "Phân loại thuộc về", "property_value": "Giá trị thuộc tính", "dictionary_value": "Giá trị từ điển", "is_default": "Có phải mặc định không", "Display Text": "Văn bản hiển thị",  "Tag Type": "Loại thẻ",  "Style (Style)": "Kiểu (Style)",  "Style (Class)": "Kiểu (Class)",  "Extended Data": "Dữ liệu mở rộng", "title": "Tiêu đề", "subtitle": "Phụ đề", "summary": "Tóm tắt", "cover_image": "Ảnh bìa", "seo_title": "Tiêu đề SEO", "seo_keywords": "Từ khóa SEO", "seo_description": "Mô tả SEO", "canonical_url": "URL chuẩn", "category": "Danh mục", "tags": "Thẻ", "status": "Trạng thái", "draft": "Bản nháp", "published": "Đã xuất bản", "offline": "Đã gỡ xuống", "is_top": "Ghim lên đầu", "is_featured": "Nổi bật", "view_count": "Lượt xem", "like_count": "Lượt thích", "is_comment_allowed": "Cho phép bình luận", "comments_count": "Số bình luận", "sort": "Sắp xếp", "modification_record": "Lịch sử chỉnh sửa", "parent_node_cannot_select_self": "Không thể chọn chính mình làm nút cha", "please_select_category": "Vui lòng chọn danh mục", "please_select_tags": "Vui lòng chọn thẻ", "extended_settings": "Cài đặt mở rộng", "seo_settings": "Cài đặt SEO", "close": "Đóng", "save": "Lưu", "content_cannot_empty": "Nội dung không được để trống", "only_images_allowed": "Chỉ cho phép hình ảnh", "image_size_exceeded": "Kích thước hình ảnh không được vượt quá 2MB", "cover_upload_success": "Tải lên ảnh bìa thành công", "cover_upload_failed": "Tải lên ảnh bìa thất bại", "image_upload_failed": "Tải lên hình ảnh thất bại"
            } 
        };
        
        Vue.prototype.i18n.messages.zhTW = { 
            ...Vue.prototype.i18n.messages.zhTW, 
            ...{ "category": "所属分类", "property_value": "属性值", "dictionary_value": "字典值", "is_default": "是否默认",  "Display Text": "顯示文本",  "Tag Type": "標籤類型",  "Style (Style)": "樣式(Style)",  "Style (Class)": "樣式(Class)",  "Extended Data": "擴展數據", "title": "標題", "subtitle": "副標題", "summary": "摘要", "cover_image": "封面圖片", "seo_title": "SEO標題", "seo_keywords": "SEO關鍵詞", "seo_description": "SEO描述", "canonical_url": "規範URL", "category": "類別", "tags": "標籤", "status": "狀態", "draft": "草稿", "published": "已發布", "offline": "已下架", "is_top": "置頂", "is_featured": "精選", "view_count": "閱讀數", "like_count": "點讚數", "is_comment_allowed": "允許評論", "comments_count": "評論數", "sort": "排序", "modification_record": "修改記錄", "parent_node_cannot_select_self": "上級節點不能選擇自己", "please_select_category": "請選擇分類", "please_select_tags": "請選擇標籤", "extended_settings": "擴展設置", "seo_settings": "SEO設置", "close": "關閉", "save": "保存", "content_cannot_empty": "內容不能為空", "only_images_allowed": "只能上傳圖片", "image_size_exceeded": "圖片大小不能超過2MB", "cover_upload_success": "封面圖片上傳成功", "cover_upload_failed": "封面圖片上傳失敗", "image_upload_failed": "圖片上傳失敗"
            } 
        };
    </script>
    <script src="~/ruoveaui/xg6rvft8p/elementui/index.min.js"></script>
    <script src="~/ruoveaui/xg6rvft8p/elementui/lang/zhCN.js"></script>
    <script src="~/ruoveaui/xg6rvft8p/elementui/lang/en.js"></script>
    <script src="~/ruoveaui/xg6rvft8p/elementui/lang/fr.js"></script>
    <script src="~/ruoveaui/xg6rvft8p/elementui/lang/ja.js"></script>
    <script src="~/ruoveaui/xg6rvft8p/elementui/lang/vi.js"></script>
    <script src="~/ruoveaui/xg6rvft8p/elementui/lang/zhTW.js"></script>
    <script>Vue.prototype.$baseURL = "@config?.PrefixRoute";</script>
    <script src="~/ruoveaui/xg6rvft8p/vue/axios.min.min.js"></script>
    <script src="~/ruoveaui/xg6rvft8p/vue/vue-i18n.min.js"></script>
    <script src="~/ruoveaui/xg6rvft8p/avue/avue.min.js"></script>
    <script src="~/ruoveaui/xg6rvft8p/avue/avue.min.option.js"></script> 
    <script src="~/wwwroot/xg6rft8p/wangeditor/index.js"></script>
  
    <script>

        new Vue({
            el: '#app',
            data() {
                return {
                    loading: true,
                    statusData : [ { label: this.i18n.t('draft'), value: 0, }, { label: this.i18n.t('published'), value: 1, }, { label: this.i18n.t('offline'), value: 2, } ],
                    yesnoData : [ { label: `${Vue.prototype.i18n.t('yes')}`, value: 1, },{ label: `${Vue.prototype.i18n.t('no')}`, value: 0, }, ],

                    editorInstance:null,
                    form: {
                        title: '',
                        subtitle: '',
                        summary: '',
                        coverImage: '',
                        seo:{
                            metaTitle: '',
                            metaKeywords: '',
                            metaDescription: '',
                            canonicalUrl: ''
                        },
                        categorieId: '',
                        tagIds: [],
                        status: 0,
                        isTop: 0,
                        isFeatured: 0,
                        isCommentAllowed: 1,
                        sort: 100,
                        content: ''
                    },
                    rules: {
                        title: [{ required: true, message: this.i18n.t('pleaseenter'), trigger: 'blur' }],
                        categorieId: [{ required: true, message: this.i18n.t('pleaseenter'), trigger: 'blur' }],
                    },

                    categoryOptions: [],
                    tagOptions: [],

                    uploadUrl: '@(config.PrefixRoute)/article/upload',

                    type:new URLSearchParams(location.search).get('type'),
                    id:new URLSearchParams(location.search).get('id')
                };
            },
            created() {
                this.loadOptions();
                this.loadDetail();
            },
            mounted() {
                this.initEditor();
            },
            methods: {
                initEditor() {
                    const editor = new wangEditor('#toolbar-container', '#editor-container');
                    editor.id=this.id;
                    editor.config.lang = Vue.prototype.i18n.currentLang;
                    editor.config.excludeMenus = ['video'];
                    editor.config.onchange = (newHtml) => { this.form.content = newHtml; };
                    editor.config.customPaste = (event, editor) => { return true; };

                    // 配置图片上传
                    editor.config.uploadImgServer = '@(config.PrefixRoute)/article/upload-image';
                    editor.config.uploadFileName = 'file';
                    editor.config.uploadImgParams = { type: 'editor' };
                    editor.config.uploadImgHooks = {
                        customInsert: function(insertImgFn, result) {
                            if (result.code==200) {
                                insertImgFn(result.data.filePath);
                            } else {
                                this.$message.error(result.message || this.i18n.t('image_upload_failed'));
                            }
                        }.bind(this)
                    };

                    this.$nextTick(() => { editor.txt.html(this.form.content || ''); });
                    editor.config.height = 800;
                    editor.create();
                    this.editorInstance = editor;
                },
                // 封面图片上传方法
                handleAvatarSuccess(res) {
                    if (res.code==200) {
                        this.form.coverImage = res.data.filePath;
                        this.$message.success(this.i18n.t('cover_upload_success'));
                    } else {
                        this.$message.error(res.message || this.i18n.t('cover_upload_failed'));
                    }
                },
    
                beforeAvatarUpload(file) {
                    const isImg = file.type.startsWith('image/');
                    const isLt2M = file.size / 1024 / 1024 < 2;
        
                    if (!isImg) {
                        this.$message.error(this.i18n.t('only_images_allowed'));
                        return false;
                    }
                    if (!isLt2M) {
                        this.$message.error(this.i18n.t('image_size_exceeded'));
                        return false;
                    }
        
                    return isImg && isLt2M;
                },
                loadOptions() {
               
                    this.loading = true;
                    this.$http.get(`/category/list`).then((res) => {
                        this.loading = false;
                        this.categoryOptions = res.filter(item => item !== null && item.id !== null);
                    }).catch(e => { this.loading = false; this.categoryOptions = []; });

                    this.$http.get(`/tag/list`).then((res) => {
                        this.loading = false;
                        this.tagOptions = res.filter(item => item !== null && item.id !== null);
                    }).catch(e => { this.loading = false; this.tagOptions = []; });

                    this.type = new URLSearchParams(location.search).get('type');
                },
                      
                loadDetail(){
                    this.loading = true;
                    const id = new URLSearchParams(location.search).get('id');
                    if(!id) return;
                    this.$http.get(`/article/data?id=${id}`).then((res) => {
                        this.loading = false;
                        this.form = Object.assign({},this.$options.data().form,res,{ seo: { ...this.$options.data().form.seo, ...(res.seo || {}) } });
                        this.$nextTick(() => {
                            if (this.editorInstance) {
                                this.editorInstance.txt.html(this.form.content || '');
                            }
                        });
                    }).catch(e => {
                       this.loading = false;
                    });

                },
                submit() {
                    this.$refs.form.validate(valid => {
                        if (!valid) return;
                        if(!this.form.content)
                        {
                            this.$message({ message: this.i18n.t('content_cannot_empty'), center: true, type: 'error',  });
                            return;
                        }
                        this.loading = true;
                        if(this.type=='add')
                        {
                            this.form.tags=this.form.tagIds	;
                            this.form.categories=[this.form.categorieId];
                            this.$http.post(`/article/add`, this.form).then((res) => {
                                if (res == true) {
                                    this.$message({ message: `${this.i18n.t('submit_success')}`, center: true, type: 'success',onClose:()=>{ setTimeout( ()=>{ this.onClose(); },1000) } });
                                }
                            }).catch(e => {
                                this.loading = true;
                            });
                        }
                        else if(this.type=='edit')
                        {
                            this.form.tags=this.form.tagIds	;
                            this.form.categories=[this.form.categorieId];
                            this.$http.post(`/article/update`, this.form).then((res) => {
                                if (res == true) {  
                                    this.$message({ message: `${this.i18n.t('submit_success')}`, center: true,offset:"50%", type: 'success',onClose:()=>{ setTimeout(()=>{ this.onClose(); },1000) } });
                                }
                            }).catch(e => {  
                                this.loading = false;
                            });
                        }
                    });
                },
                onClose() {
                    if (parent && parent.article && parent.article.onClose) {
                        parent.article.onClose();
                    }
                },
                beforeDestroy()
                {
                    if (this.editorInstance && this.editorInstance.destroy) {
                        this.editorInstance.destroy();
                    }
                },
            },
        });
    </script>
</body>
</html>